<template>
  <div class="pdf-viewer">
    <canvas ref="pdfCanvas"></canvas>
    <div class="pdf-controls">
      <button @click="prevPage" :disabled="currentPage <= 1">上一页</button>
      <span>{{ currentPage }} / {{ totalPages }}</span>
      <button @click="nextPage" :disabled="currentPage >= totalPages">下一页</button>
    </div>
  </div>
</template>

<script>
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist';

export default {
  name: 'PDFViewer',
  props: {
    file: {
      type: Object | File,
      required: true
    },
    fileData: {
      type: [ArrayBuffer, null],
      required: true
    }
  },
  data() {
    return {
      pdfDoc: null,
      currentPage: 1,
      totalPages: 0,
      scale: 1.5
    };
  },
  mounted() {
    // 设置 PDF.js worker 路径
    GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js';

    if (this.fileData) {
      this.loadPDF();
    }
  },
  watch: {
    fileData() {
      if (this.fileData) {
        this.loadPDF();
      }
    }
  },
  methods: {
    async loadPDF() {
      try {
        const typedArray = new Uint8Array(this.fileData);
        this.pdfDoc = await getDocument(typedArray).promise;
        this.totalPages = this.pdfDoc.numPages;
        this.currentPage = 1;
        this.renderPage(this.currentPage);
      } catch (error) {
        console.error('PDF 加载失败:', error);
        this.$emit('error', 'PDF 加载失败');
      }
    },

    async renderPage(pageNumber) {
      if (!this.pdfDoc) return;

      try {
        const page = await this.pdfDoc.getPage(pageNumber);
        const viewport = page.getViewport({ scale: this.scale });

        const canvas = this.$refs.pdfCanvas;
        const context = canvas.getContext('2d');

        canvas.height = viewport.height;
        canvas.width = viewport.width;

        const renderContext = {
          canvasContext: context,
          viewport: viewport
        };

        await page.render(renderContext).promise;
      } catch (error) {
        console.error('PDF 页面渲染失败:', error);
        this.$emit('error', 'PDF 页面渲染失败');
      }
    },

    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.renderPage(this.currentPage);
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.renderPage(this.currentPage);
      }
    }
  }
};
</script>

<style scoped>
.pdf-viewer {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.pdf-controls {
  margin-top: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.pdf-controls button {
  background-color: #2196F3;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.pdf-controls button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>